<template>
  <div>
    <panel title="用户管理" :total="total" @page="pageClick" :showAdd="true" @add="addClick">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%">
        <el-table-column
          prop="name"
          label="用户名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="description"
          label="昵称">
        </el-table-column>
        <el-table-column
          width="60"
          label="头像">
          <template slot-scope="scope">
            <img class="avatar-img" :src="fileServer + scope.row.image" @click="previewImg(scope.row.image)" alt="">
          </template>
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
          <template slot-scope="scope">
            {{ getRoleName(scope.row)}}
          </template>
        </el-table-column>
        <el-table-column
          width="60"
          label="状态">
          <template slot-scope="scope">
            {{scope.row.disabled == 0 ? '启用' : '禁用'}}
          </template>
        </el-table-column>
        <el-table-column
          label="登陆时间">
          <template slot-scope="scope">
            {{scope.row.time | time}}
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <i class="el-icon-menu" @click="authUser(scope.row)" title="菜单授权"></i>
            <i class="el-icon-edit-outline" @click="modifyRow(scope.row)" title="编辑"></i>
            <i class="el-icon-delete" @click="deleteRow(scope.row)" title="删除"></i>
          </template>
        </el-table-column>
      </el-table>
    </panel>

    <el-dialog  :title="isEdit ? '编辑用户' : '新增用户'" :visible.sync="dialogVisible" width="500px" >
      
      <el-form :model="adminForm"    label-width="100px"  >
        <el-form-item label="用户名:"  :required="true"  >
          <el-input v-model.trim="adminForm.name" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="昵称:"   :required="true" >
          <el-input v-model.trim="adminForm.description"></el-input>
        </el-form-item>
        <el-form-item label="密码:"   v-if="!isEdit" :required="true" >
          <el-input v-model.trim="adminForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="角色:"  :required="true" >
          <el-checkbox-group v-model="adminForm.roles">
            <el-checkbox v-for="tt in typeOption" :label="tt.label" :key="tt.label">{{tt.value}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态:"  :required="true" >
          <el-switch  v-model="adminForm.state" > </el-switch>
          <span style="margin-left:20px;">{{!adminForm.state ? '禁用' : '启用'}}</span>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="菜单授权" :visible.sync="authDialog" width="500px">
      <auth-menu :uid="authAdmin"></auth-menu>
      <span slot="footer" class="dialog-footer">
        <el-button @click="authDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitAuth()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="图片预览" :visible.sync="imgDialog" width="500px">
      <img :src="imgPreview" width="100%"  alt="">
    </el-dialog>

  </div>
  
</template>

<script>
import Admin from "@/api/user";
import Menu from "@/api/menu";
import AuthMenu from "@/components/AuthMenu";
import { mapState } from "vuex";
import format from 'date-fns/format'
import Config from '@/utils/config'
export default {
  name: "userMgr",
  data() {
    return {
      loading: true,
      current: 1,
      pageSize: 10,
      total: 0,
      isEdit: false,
      dialogVisible: false,
      authDialog: false,
      authAdmin: 0,
      typeOption: [
        {
          label: "ROLE_ADMIN",
          value: "管理员"
        },
        {
          label: "ROLE_USER",
          value: "普通用户"
        }
      ],
      adminForm: {
        roles: []
      },
      tableData: [],
      fileServer: Config.fileServer,
      imgDialog:false,
      imgPreview : ''
    };
  },

  filters: {
    time(val) {
      return format(new Date(val),'YYYY-MM-DD HH:mm:SS')
    }
  },

  components: { AuthMenu },

  computed: { ...mapState(["authMenus"]) },

  methods: {
    previewImg(img){
      this.imgPreview = this.fileServer + img;
      this.imgDialog = true;
    },
    getRoleName(row) {
      if (!row.role_name) {
        return "";
      }
      var role_arr = [];
      row.role_name.split(",").forEach(role => {
        if (role == "ROLE_ADMIN") {
          role_arr.push("管理员");
        } else if (role == "ROLE_USER") {
          role_arr.push("用户");
        }
      });
      return role_arr.join(",");
    },
    getUserList() {
      this.loading = true;
      Admin.getUserList({ index: this.current - 1, limit: this.pageSize })
        .then(data => {
          this.loading = false;
          this.total = data.total;
          this.tableData = data.list;
        })
        .catch(err => {});
    },
    pageClick(page) {
      this.current = page;
      this.getUserList();
    },
    addClick() {
      this.isEdit = false;
      this.adminForm = { roles: ["ROLE_USER"], state: true };
      this.dialogVisible = true;
    },
    submitForm() {
      if (!this.adminForm.name) {
        this.$message.error("用户名必填");
        return false;
      }

      if (!this.adminForm.description) {
        this.$message.error("昵称必填");
        return false;
      }

      if (!this.adminForm.roles || this.adminForm.roles.length == 0) {
        this.$message.error("请至少选择一种用户角色");
        return false;
      }

      this.adminForm.role_name = this.adminForm.roles.join(",");
      this.adminForm.disabled = this.adminForm.state ? 0 : 1;

      if (this.isEdit) {
        Admin.modifyUser(this.adminForm)
          .then(data => {
            this.dialogVisible = false;
            this.$message({ message: "修改成功", type: "success" });
            this.getUserList();
          })
          .catch(err => {
            this.$message.error("修改失败");
          });
      } else {
        if (!this.adminForm.password) {
          this.$message.error("密码必填");
          return false;
        }
        Admin.addUser(this.adminForm)
          .then(data => {
            this.dialogVisible = false;
            this.$message({ message: "新增成功", type: "success" });
            this.getUserList();
          })
          .catch(err => {
            if (err.code == 2) {
              this.$message.error("该用户名已存在");
            } else {
              this.$message.error("新增失败");
            }
          });
      }
    },
    modifyRow(row) {
      this.isEdit = true;
      this.dialogVisible = true;
      this.adminForm = Object.assign(
        { roles: row.role_name.split(",") },
        { state: !row.disabled },
        row
      );
    },
    deleteRow(row) {
      this.$confirm("此操作将永久删除所选用户,确定继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        Admin.deleteUser(row.name)
          .then(data => {
            if (this.tableData.length == 1 && this.current > 1) {
              this.current -= 1;
            }
            this.$message({ message: "删除成功", type: "success" });
            this.getUserList();
          })
          .catch(err => {
            this.$message.error("删除失败");
          });
      });
    },
    authUser(row) {
      this.authDialog = true;
      this.authAdmin = row.id;
    },
    submitAuth() {
      Menu.authMenu(this.authAdmin, this.authMenus)
        .then(data => {
          this.$message({ message: "菜单授权成功", type: "success" });
          this.authDialog = false;
        })
        .catch(err => {
          this.$message.error("菜单授权失败");
        });
    }
  },

  mounted() {
    this.getUserList();
  }
};
</script>
<style rel="stylesheet/less" lang="less" scoped>
.avatar-img{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
</style>
